package cn.edu.sdju.wanglo1911.team10.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.sdju.wanglo1911.team10.dao.BookDao;
import cn.edu.sdju.wanglo1911.team10.dao.ShoppingCartItemDao;
import cn.edu.sdju.wanglo1911.team10.po.Book;
import cn.edu.sdju.wanglo1911.team10.po.ShoppingCartItem;

@Service
public class ShoppingCartImpl implements ShoppingCartService {

	
	@Autowired
	private ShoppingCartItemDao shoppingCartItemDao;
	@Autowired
	private BookDao bookDao;
	public List<ShoppingCartItem> getAllItemByUserId(String userId) {
		// TODO Auto-generated method stub
		return shoppingCartItemDao.getAllItemByUserId(userId);
	}
	
	@Transactional
	public boolean insertItem(ShoppingCartItem item) {
		// TODO Auto-generated method stub
				Book book = bookDao.getBookById(item.getBookId());
				if (book.getStock() >= item.getAmount()) {
					book.setStock(book.getStock()-item.getAmount());
					bookDao.updateBook(book);
					ShoppingCartItem olderItem = shoppingCartItemDao.getItemById(item);
					if (olderItem == null) {
						shoppingCartItemDao.insertItem(item);
					} else {
						olderItem.setAmount(olderItem.getAmount() + item.getAmount());
						shoppingCartItemDao.updateItem(olderItem);
					}
					return true;		
				} else {
					return false;
				}
	}

	public void updateItem(ShoppingCartItem item) {
		// TODO Auto-generated method stub
		shoppingCartItemDao.updateItem(item);
	}

	public void deleteAllByUserId(String userId) {
		// TODO Auto-generated method stub
		shoppingCartItemDao.deleteAllByUserId(userId);
	}
	@Transactional
	public void deleteItem(ShoppingCartItem item) {
		// TODO Auto-generated method stub
		Book book = bookDao.getBookById(item.getBookId());
		book.setStock(item.getAmount() + book.getStock());
		bookDao.updateBook(book);
		shoppingCartItemDao.deleteItem(item);
	}

	public ShoppingCartItem getItemById(ShoppingCartItem item) {
		// TODO Auto-generated method stub
		return shoppingCartItemDao.getItemById(item);
	}

}
